package com.example.map.rx1demo.learns;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by qundui on 2017/6/5.
 */

public class DownImageUtils {
    OkHttpClient okHttpClient;
    public Observable<byte[]> DownImage(final String Path){
//        return Observable.create(new Observable.OnSubscribe<String>() {
//            @Override
//            public void call(final Subscriber<? super String> subscriber) {
//                  if (!subscriber.isUnsubscribed()){
//                    okHttpClient=new OkHttpClient();
//                      final Request r=new Request.Builder().url(Path).build();
//                     okHttpClient.newCall(r).enqueue(new Callback() {
//                         @Override
//                         public void onFailure(Call call, IOException e) {
//                             subscriber.onError(e);
//                         }
//
//                         @Override
//                         public void onResponse(Call call, Response response) throws IOException {
//                             byte[] bytes = response.body().bytes();
//                             if (bytes.length>0){
//                                 subscriber.onNext(response.body().string());
//                             }
//                             subscriber.onCompleted();
//                         }
//                     });
//                  }
//            }
//        });
        return Observable.create(new Observable.OnSubscribe<byte[]>() {
            @Override
            public void call(final Subscriber<? super byte[]> subscriber) {
                if (!subscriber.isUnsubscribed()){
                    okHttpClient=new OkHttpClient();
                      final Request r=new Request.Builder().url(Path).build();
                     okHttpClient.newCall(r).enqueue(new Callback() {
                         @Override
                         public void onFailure(Call call, IOException e) {
                             subscriber.onError(e);
                         }

                         @Override
                         public void onResponse(Call call, Response response) throws IOException {

                             if (response.isSuccessful()){
                                 subscriber.onNext(response.body().bytes());
                             }
                             subscriber.onCompleted();
                         }
                     });
                  }
            }
        });
    }
}
